package com.ermao.learnWebmagic.processor_2;

import com.ermao.learnWebmagic.config.BilibiliAPIEnum;
import com.ermao.learnWebmagic.config.Config;
import com.ermao.learnWebmagic.entity.UP;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.Json;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

public class UPPageHandler {

	public void handle(Page page, CopyOnWriteArrayList<UP> result) {
		String curUrl = page.getRequest().getUrl();
		Json json = page.getJson();

		if (curUrl.startsWith(BilibiliAPIEnum.SEARCH.getUrlPrefix())) {
			// 获取UP 主的 mid 的并且拼接出 UP 主主页 URL
			List<String> midList = json.jsonPath("$.data.result[*].mid").all();
			midList = midList.stream().distinct().limit(Config.UP_NUMS).collect(Collectors.toList());

			for (String mid : midList) {
				Request UPStatReq = new Request();
				Request UpInfoReq = new Request();
				UP up = new UP();

				UPStatReq.setUrl(BilibiliAPIEnum.getAPI(BilibiliAPIEnum.UP_STAT, mid));
				UpInfoReq.setUrl(BilibiliAPIEnum.getAPI(BilibiliAPIEnum.UP_INFO, mid));

				UPStatReq.putExtra(Config.EXTRA, up);
				UpInfoReq.putExtra(Config.EXTRA, up);

				page.addTargetRequest(UPStatReq);
				page.addTargetRequest(UpInfoReq);
			}

		} else if (curUrl.startsWith(BilibiliAPIEnum.UP_INFO.getUrlPrefix())) {
			// 查询 UP 主的 INFO

			UP up = page.getRequest().getExtra(Config.EXTRA);
			String upName = json.jsonPath("$.data.name").toString();
			String mid = json.jsonPath("$.data.mid").toString();
			up.setUp_name(upName);
			up.setMid(mid);

			afterHandle(up, result);

		} else if (curUrl.startsWith(BilibiliAPIEnum.UP_STAT.getUrlPrefix())) {
			// 查询 UP 主的 STAT

			UP up =  page.getRequest().getExtra(Config.EXTRA);
			String follower = json.jsonPath("$.data.follower").toString();
			up.setFollowers(Integer.parseInt(follower));

			afterHandle(up, result);
		}
	}



	private void afterHandle(UP up, CopyOnWriteArrayList<UP> result) {
		if (up.getMid() != null && up.getFollowers() != null && up.getUp_name() != null) {
			result.add(up);
		}
	}
}
